#include <iostream>
#include <memory>
//#include <string>
using std::cout;
using std::endl;
using namespace std;

class Point 
: public std::enable_shared_from_this<Point> 
{
public:
	//...
    Point(int x = 0, int y = 0)
        :_ix(x)
        ,_iy(y){
        std::cout << "构造Point(" << x << "," << y << ") @" << this << std::endl;
    }

    ~Point() {
        std::cout << "析构Point @" << this << std::endl;
    }

    void print() const {
        std::cout << "Point(" << _ix << "," << _iy << ") @" << this << std::endl;
    }

	shared_ptr<Point> addPoint(Point & pt) {
		_ix += pt._ix;
		_iy += pt._iy;
		return shared_from_this();
	}
private:
    int _ix;
    int _iy;
};

void test0(){
    //需要人为注意避免
    Point * pt = new Point(1,2);
    unique_ptr<Point> up(pt);
    if(up){
        std::cout << "up 指向: ";
        up->print();
    }

    // unique_ptr<Point> up2(pt);   // core dumped
    unique_ptr<Point> up2 = move(up);
    if(up){                         // 未显示, up已空
        std::cout << "up 指向: ";
        up->print();
    }
    if(up2){
        std::cout << "up2 指向: ";
        up2->print();
    }
}

void test1(){ //error
    unique_ptr<Point> up(new Point(1,2));
    unique_ptr<Point> up2(new Point(1,2));
    if(up){
        std::cout << "up 指向: ";
        up->print();
    }
    if(up2){
        std::cout << "up2 指向: ";
        up2->print();
    }

    //让两个unique_ptr对象托管了同一片空间
    /*
    up.reset(up2.get());
    if(up){
        std::cout << "up 指向: ";
        up->print();
    }
    if(up2){
        std::cout << "up2 指向: ";
        up2->print();
    }
    */
}

void test2(){
    shared_ptr<Point> sp(new Point(1,2));    
    shared_ptr<Point> sp2(new Point(3,4));

    //创建sp3的参数实际上是sp所对应的裸指针
    //效果还是多个智能指针托管了同一块空间
    shared_ptr<Point> sp3(sp->addPoint(*sp2));
    cout << "sp3 = ";
    sp3->print();
}

int main()
{
    test0();
    test1();
    test2();
    return 0;
}

